package com.thingsgrid.appmanager.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.thingsgrid.common.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 功能说明：远程命令处理器
 *
 * @author 李龙飞
 * @since 2019/8/22 17:42
 */
@Slf4j
public class ShellProcessor {

	private static volatile ShellProcessor shellProcessor;

	private ShellProcessor(){}

	//单例实例化该类
	public static ShellProcessor getInstance(){
		if(null==shellProcessor){
			synchronized (ShellProcessor.class){
				if(null==shellProcessor){
					shellProcessor = new ShellProcessor();
				}
			}
		}
		return shellProcessor;
	}

	/**
	 *说明：ssh远程登录
	 *@author lilongfei
	 *@since 2019/8/22 17:56
	 */
	public Connection login(){
		Connection connection = null;
		try {
			connection = new Connection(CommonConstant.SSH_IP);
			connection.connect();
			boolean connectionFlag = connection.authenticateWithPassword(CommonConstant.SSH_USERNAME,CommonConstant.SSH_PASSWORD);
			if(connectionFlag){
				log.info("SSH登录成功！");
				return connection;
			}
		} catch (IOException e) {
			log.error("SSH登录失败");
			connection.close();
			e.printStackTrace();
		}
		return connection;
	}

	/**
	 *说明：执行ssh命令
	 *@author lilongfei
	 *@since 2019/8/22 17:57
	 */
	public String execmd(Connection connection,String cmd){
		String result = "";
		try {
			if(connection!=null){
				String defaultCharset = "UTF-8";
				Session session = connection.openSession();
				session.execCommand(cmd);
				result = processStdout(session.getStdout(), defaultCharset);
				connection.close();
				session.close();
			}
		} catch (IOException e) {
			System.out.println("命令执行失败");
			e.printStackTrace();
		}
		return result;
	}

	/**
	 *说明：解析脚本
	 *@author lilongfei
	 *@since 2019/8/22 17:58
	 */
	private String processStdout(InputStream in, String charset){
		InputStream stdout = new StreamGobbler(in);
		StringBuilder builder = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset));
			String line;
			while((line=br.readLine())!=null){
				builder.append(line).append("\n");
			}
			br.close();
		} catch (UnsupportedEncodingException e) {
			System.out.println("脚本解析错误");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

}
